package com.example.rabbitmq.service.impl;

import com.example.rabbitmq.config.RabbitConfig;
import com.example.rabbitmq.service.RabbitMQService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class RabbitMQServiceImpl implements RabbitMQService {
    //日期格式化
    private static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public String sendMsg(String msg) {
        try {
            String msgID= UUID.randomUUID().toString().replace("-","").substring(0,32);
            String sendTime =sdf.format(new Date());
            Map<String,Object> map=new HashMap<>();
            map.put("msgId",msgID);
            map.put("sendTime",sendTime);
            map.put("msg",msg);
            rabbitTemplate.convertAndSend(RabbitConfig.RABBIT_DEMO_DIRECT_EXCHANGE,RabbitConfig.RABBITMQ_DEMO_DIRECT_ROUTING,map);
            return "OK";
        }catch (Exception ex){
            ex.printStackTrace();
            return "error";
        }
    }
}
